Java/J2EE and SOA (349 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (16 Blogs)
  • Comprehensive Java Course (5 Blogs)
  • Java/J2EE and SOA (346 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

Introduction to Java Servlets – Servlets in a Nutshell

Last updated on Jun 17,2021 38.7K Views

A tech enthusiast in Java, Image Processing, Cloud Computing, Hadoop. A tech enthusiast in Java, Image Processing, Cloud Computing, Hadoop.
4 / 22 Blog from Advance Java

In this modern era of the internet, billion bytes of data is generated on a day-to-day basis. To gain access to this humongous amount of data, every person is required to send a request on the network and await a response. Most of us believe in the misconception that all of these web applications are created over web frameworks like HTML, PHP, JavaScript etc. But, did you know, web applications can be based on Java using a service called Java Servlets? In this article, let’s delve deep into Java Servlets and understand how this technology is useful for creating a web application.

Below is the list of topics that I will be covering in this Java Servlets tutorial:

You may also go through this recording of Java Servlets Tutorial where you can understand the topics in a detailed manner with examples.

Java Servlets Tutorial | Introduction to Servlets | Edureka

This video will talk about the basics of the World Wide Web and its components. It will tell you the fundamental concepts of servlets, its life cycle and various steps to create Servlet. 

Before we jump into servlets, let’s understand a few fundamentals of Web.

Introduction to Web

Web is basically a system of Internet servers that supports formatted documents. The documents are formatted using a markup language called HTML (HyperText Markup Language) that supports links to other documents, like graphics, audio, and video files.

Introduction to Web-Java Servlets-EdurekaWeb consists of billions of clients and servers connected through wires and wireless networks. First, web clients make requests to a web server. Then, the web server receives the request, finds the resources and returns the response to the client. When a server answers a request, it usually sends some type of content to the client. Then, the client uses a web browser to send a request to the server. The server often sends a response back to the browser with a set of instructions written in HTML. All browsers know how to display HTML pages to the client.

Basically, this is all about the backend working of the WWW (World Wide Web). Now, let’s understand the connectivity between Web & HTTP.

Web & HTTP

A website is a collection of static files i.e. web pages such as HTML pages, images, graphics etc. A Web application is a website with dynamic functionality on the server. GoogleFacebookTwitter are examples of web applications.

So, what is the link between the Web and HTTP? Let’s now find out.

Web & Http-Java Servlets-EdurekaHTTP (Hypertext Transfer Protocol)

  • HTTP is a protocol that clients and servers on the web to communicate.
  • It is similar to other internet protocols such as SMTP (Simple Mail Transfer Protocol) and FTP (File Transfer Protocol.
  • HTTP is a stateless protocol i.e it supports only one request per connection. This means that with HTTP the clients connect to the server to send one request and then disconnect. This mechanism allows more users to connect to a given server over a period of time.
  • The client sends an HTTP request and the server answers with an HTML page to the client, using HTTP.

The HTTP request can be made using a variety of methods, but the ones which we use widely are  Get and Post. The method name itself tells the server the kind of request that is being made, and how the rest of the message will be formatted.

Now, with the help of the below table, let’s understand the difference between Get and Post methods of HTTP.

GetPost
1.  Data is sent in the header body1.  Data is sent in the request body
2.  Restricted to limited data transfer2.  Supports a large amount of data transfer
3.  It is not secured3.  It is completely secured
4.  It can be bookmarked4. It cannot be bookmarked

Now, that you have learned a few basics of web, let’s jump to the core topic and understand the concept of a servlet.

Java Servlets: Introduction to Servlets

A servlet is a Java Programming language class that is used to extend the capabilities of servers that host applications accessed by means of a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by web servers. It is also a web component that is deployed on the server to create a dynamic web page.

Servlets-Introduction to Java Servlets - EdurekaIn this figure you can see, a client sends a request to the server and the server generates the response, analyses it and sends the response to the client.

So, before we jump into the depth of Servlets, let’s see the technology that was used before servlets came into the picture.

CGI vs Servlets

Before servlets, we had CGI i.e. Common Gateway Interface. It is a standard way for a Web server to pass a user’s request to an application program and receives the response to forward to the user. When the user requests a Web page, the server sends back the requested page. However, when a user fills out a form on a Web page and sends it in, it is processed by an application program. The Web server typically passes the form information to a small application program. This program processes the data and sends back a confirmation message. This process of passing data back and forth between the server and the application is called the common gateway interface (CGI). It is part of the Web’s Hypertext Transfer Protocol.

But, why did we stopped using it and switched to servlets? Let’s understand this with the help of the below table:

Basis for ComparisonCommon Gateway InterfaceServlets
1. BasicPrograms are written in the native OS.Programs employed using Java.
2. Platform dependencyPlatform dependentDoes not rely on the platform
3. Creation of processEach client request creates its own process.Processes are created depending on the type of the client request.
4. Conversion of the scriptPresent in the form of executables (native to the server OS).Compiled to Java Bytecode.
5. Runs onSeparate processJVM
6. SecurityMore vulnerable to attacks.Can resist attacks.
7. SpeedSlowerFaster
8. Processing of scriptDirectBefore running the scripts it is translated and compiled.
9. PortabilityCannot be portedPortable

I hope that based on the above comparison, one can conclude, why Servlets are being used for Web Applications. Now, let’s move ahead with this article and understand Servlet Architecture.

Subscribe to our youTube channel to get new updates..!

Java Servlets: Servlet Architecture

The architecture, here, discusses the communication interface, protocol used, requirements of client and server, the programming with the languages and software involved. Basically, it performs the below-mentioned tasks.

  • First, it reads the explicit data sent by the clients (browsers).  This data can include an HTML form on a Web page, an applet or a custom HTTP client program. It also reads implicit HTTP request data sent by the clients (browsers). This can include cookies, media types and compression schemes the browser understands, and so forth.
    Servlet Architecture-Java Servlets-Edureka
  • After that, the servlet processes the data and generate the results. This process may require communicating to a database, executing an RMI, invoking a Web service, or computing the response directly.
  • After processing, it sends the explicit data (i.e., the document) to the clients (browsers). This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images), or Excel formats.
  • Finally, it also sends the implicit HTTP response to the clients (browsers). This includes telling the browsers or other clients what type of document is being returned.

Now, let’s understand the various methods in the life cycle of a servlet.

Servlet Life Cycle

The Servlet life cycle mainly includes the following four stages,

  • Loading a Servlet
  • Initializing the Servlet
  • Request handling
  • Destroying the Servlet

Servlet Life Cycle -Java Servlets-Edureka

  1. When the web server (e.g. Apache Tomcat) starts up, the servlet container deploy and loads all the servlets.
  2. The servlet is initialized by calling the init() method. The Servlet.init() method is called by the Servlet container to indicate that this Servlet instance is instantiated successfully and is about to put into service.
  3. The servlet then calls service() method to process a client’s request. This method is invoked to inform the Servlet about the client requests.
  4. The servlet is terminated by calling the destroy().
  5. The destroy() method runs only once during the lifetime of a Servlet and signals the end of the Servlet instance.


init() and destroy() methods are called only once. Finally, a servlet is garbage collected by the garbage collector of the JVM. So this concludes the life cycle of a servlet. Now, let me guide you through the steps of creating java servlets.

Java Servlets: Steps to Create Servlet

  1. Create a directory structure
  2. Create a Servlet
  3. Compile the Servlet
  4. Add mappings to the web.xml file
  5. Start the server and deploy the project
  6. Access the servlet

Now, based on the above steps, let’s write a program and understand how a servlet works.

To run a servlet program, we should have Apache Tomcat Server installed and configured. Eclipse for Java EE provides in-built Apache Tomcat. Once the server is configured, you can start with your program. One important point to note – for any servlet program, you need 3 files – index.html file, Java class file, and web.xml file. The very first step is to create a Dynamic Web Project and then proceed further.

Now, let’s see how to add 2 numbers using servlets and display the output in the browser.

First,  I will write index.html file

<!DOCTYPE HTML> 
<html> 
<body> 


<form action = "add"> 
Enter 1st number: <input type="text" name ="num1">
 Enter 2nd number: <input type="text" name="num2">
 </form>


</body> 
</html>

Above program creates a form to enter the numbers for the addition operation. Without the Java class file, you can’t perform addition on 2 numbers. So let’s now create a class file.


package edureka;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Add extends HttpServlet{
public void service(HttpServletRequest req, HttpServletResponse res) throws IOException
{
int i = Integer.parseInt(req.getParameter("num1"));
int j = Integer.parseInt(req.getParameter("num2"));
int k= i+j;
PrintWriter out = res.getWriter();
out.println("Result is"+k);
}
}

After writing the Java class file, the last step is to add mappings to the web.xml file. Let’s see how to do that.

The web.xml file will be present in the WEB-INF folder of your web content. If it is not present, then you can click on Deployment Descriptor and click on Generate Deployment Descriptor Stub. Once you get your web.xml file ready, you need to add the mappings to it. Let’s see how mapping is done using the below example:


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>Basic</display-name>
<servlet>
<servlet-name>Addition</servlet-name>
<servlet-class>edureka.Add</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Addition</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

Once done, you can execute the program by starting the server and get the desired output on the browser.

Let’s take another example where I will be creating a simple login servlet. Again, the very first step will be to write html file.

<!DOCTYPE html>
<html>
<body>


<form action="Login" method="post">


<table>


<tr>


<td><font face="Noto Serif" size="2px">Name:</font></td>




<td><input type="text" name="userName"></td>


</tr>




<tr>


<td><font face="Noto Serif" size="2px">Password:</font></td>




<td><input type="password" name="userPassword"></td>


</tr>


</table>


<input type="submit" value="Login">
</form>


</body>
</html>

Next, let’s code the Java Class file.


package Edureka;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Login extends HttpServlet
{
protected void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
{
PrintWriter pw=res.getWriter();
res.setContentType("text/html");
String user=req.getParameter("userName");
String pass=req.getParameter("userPassword");
pw.println("Login Success...!");
if(user.equals("edureka") && pass.equals("edureka"))
pw.println("Login Success...!");
else
pw.println("Login Failed...!");
pw.close();
}
}

In the above code, I have set a condition – if username and password are both equal to edureka, only then it will display successfully logged in, else login will be denied.

Let’s add the mappings to the web.xml file now.

<?xml version="1.0"encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"version="3.1">
<display-name>LoginServlet</display-name>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Edureka.Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

So, this is how a servlet is created and configured. Let’s now see what a Generic servlet is and how is it created.

Generic Servlets

A Generic servlet is a protocol-independent servlet that should always override the service() method to handle the client request. The service() method accepts two arguments, ServletRequest object, and ServletResponse object. The request object tells the servlet about the request made by the client while the response object is used to return a response back to the client. GenericServlet is an abstract class and it has only one abstract method, which is service(). That’s why when we create a Generic Servlet by extending the GenericServlet class, we must override the service() method.

Now, let’s see how to create and invoke a Generic servlet. Again I will code 3 files as shown below:

1. HTML file

We are creating an HTML file that will call the servlet once we click on the link on the web page. Create this file in the WebContent folder. The path of this file should look like this: WebContent/index.html

<html>
<title>Generic Servlet Demo</title>
</head>
<body>
<a href="welcome">Click here to call Generic Servlet</a>
</body>
</html>

2. Java Class file

Here we will be creating a Generic Servlet by extending GenericServlet class. When creating a GenericServlet, you must override the service() method. Right click on the src folder and create a new class file and name the file as generic. The file path should look like this: Java Resouces/src/default package/generic.java


package EdurekaGeneric;
import java.io.*;
importjavax.servlet.*;
public class generic extends GenericServlet{
public void service(ServletRequest req,ServletResponse res) throws IOException,ServletException{
res.setContentType("text/html");
PrintWriter pwriter=res.getWriter();
pwriter.print("<html>");
pwriter.print("<body>");
pwriter.print("

<h2>Generic Servlet Example</h2>


");
pwriter.print("Welcome to Edureka YouTube Channel");
pwriter.print("</body>");
pwriter.print("</html>");
}
}

3. web.xml
This file can be found at this path WebContent/WEB-INF/web.xml. In this file we will map the Servlet with the specific URL. Since we are calling the welcome page upon clicking the link on index.html, it will map the welcome page to the Servlet class that we have already created above.


<?xml version="1.0"encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://xmlns.jcp.org/xml/ns/javaee"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd/"version="3.1"/>
<display-name>LoginServlet</display-name>
<servlet>
<servlet-name>MyGenericServlet</servlet-name>
<servlet-class>EdurekaGeneric.generic</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyGenericServlet</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

After this, start your Tomcat Server and run the servlet. You will get the desired output.
Now, let’s jump into the last section of this article, and see useful classes and interfaces of java servlets.

Java Servlets: Servlet Classes & Interfaces

Servlet API consists of two important packages that encapsulate all the important classes and interfaces, namely:

  • javax.servlet
  • javax.servlet.http

With the help of below table let’s see some important classes and Interfaces of a servlet.

ServletDeclares LifeCycle methods of the servlet
ServletConfigAllows the servlet to get initialization methods
ServletContextEnables the servlet to log access and access information
ServletRequestUsed to read data from the client request
ServletResponseUsed to write data to clients response
GenericServletImplements Servlet and Servlet.Config Interface
ServletInputStreamProvides input stream to read requests from the client
ServletOutputStreamProvides output stream to write responses to the client
ServletExceptionIndicates that the servlet is not available
HttpServletProvides methods to handle HTTP Request & Response

This brings us to the end of our blog on Introduction to Java Servlets.  I hope you found this blog informative and added value to your knowledge.

Get Certified With Industry Level Projects & Fast Track Your Career

Check out the Java Certification Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this “Java Servlet” blog and we will get back to you as soon as possible.

Upcoming Batches For Java Course Online
Course NameDateDetails
Java Course Online

Class Starts on 7th December,2024

7th December

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

Introduction to Java Servlets – Servlets in a Nutshell

edureka.co